package com.boot.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.boot.entity.Concern;
import com.boot.entity.Store;
import com.boot.entity.StoreImage;
import com.boot.entity.StoreVideo;
import com.boot.mapper.ConcernDao;
import com.boot.mapper.StoreDao;
import com.boot.service.StoreService;
import com.boot.util.*;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;




@Service("storeService")
public class StoreServiceImpl extends ServiceImpl<StoreDao, Store> implements StoreService {
	
	@Resource
	private StoreDao storeDao;
	@Resource
	private ConcernDao concernDao;

	public AdResult createStore(Store store) {
		AdResult result=new AdResult();
		//调用创建我的店的接口返回一个结果码
		int resultcode=storeDao.createStore(store);
		if(resultcode>0){
			//创建成功
			result.setMsg("创建成功");
			result.setStatus(1);
		}else{
			//创建失败
			result.setMsg("创建失败");
			result.setStatus(0);
		}
		return result;
	}

	@Override
	public AdResult updateStore(Store store,HttpServletRequest request,CommonsMultipartFile[] files) {
		AdResult result=new AdResult();
		/*
		 * 压缩图片业务 
		 */
		//多张店面的展示图片组合成的字符串
		String lastPhotos=store.getPhotos();
		System.out.println(lastPhotos);
		//获取项目的根目录
		String projectPath=request.getSession().getServletContext().getRealPath(File.separator);
		//是否上传了文件
		if(files.length>0){
			//上传了文件,循环遍历文件
			for(int i=0;i<files.length;i++){
				//定义将要存储的图片的名称：采用用户的id号和当前系统毫秒时间组合
				Date now=new Date();
				String dbPath="upload"+File.separator+"storephotos"+File.separator+store.getStore_id()+now.getTime();
				//压缩并上传图片
				CompressImageUtil.compressByWH(files[i],projectPath+dbPath);
				//表示最后一张图片
				lastPhotos=lastPhotos+dbPath+",";
			}
		}else{
			//未上传文件
		}
		//System.out.println(filespath);
		store.setPhotos(lastPhotos);
		//修改我的店的信息
		int resultcode=storeDao.updateStore(store);
		if(resultcode>0){
			//修改成功
			result.setMsg("修改成功");
			result.setStatus(1);
		}else{
			//修改失败
			result.setMsg("修改失败");
			result.setStatus(0);
		}
		return result;
	}
	
	
	public AdResult updateStore(Store store) {
		AdResult result=new AdResult();
		String lastPhotos=store.getPhotos();
		System.out.println(lastPhotos);
		int resultcode=storeDao.updateStore(store);
		if(resultcode>0){
			result.setMsg("修改成功");
			result.setStatus(1);
		}else{
			result.setMsg("修改失败");
			result.setStatus(0);
		}
		return result;
	}

	@Override
	public AdCommentsResult getStore(String storeid,String user_id) {
		AdCommentsResult result=new AdCommentsResult();
		//查找我的店
		Store store=storeDao.getStore(storeid);
		if(store!=null){
			List<StoreVideo> storeVideos=storeDao.selectStoreVideoByStoreId(storeid);
			store.setStoreVideos(storeVideos);
			Concern concern=new Concern();
		    concern.setStore_id(store.getStore_id());
		    concern.setUser_id(user_id);
		    Concern concernGeted=concernDao.getConcern(concern);
		    if(concernGeted!=null){
		    	result.setIsConcerned(1);
		    }else{
		    	result.setIsConcerned(0);
		    }
			//查找成功
			result.setData(store);
			result.setMsg("查找成功");
			result.setStatus(1);
		}else{
			//查找失败
			result.setMsg("查找失败");
			result.setStatus(0);
		}
		return result;
	}

	@Override
	public AdResult updateStoreIcon(Store store,HttpServletRequest request,CommonsMultipartFile file) {
		AdResult result=new AdResult();
		//我的事业的背景照片在数据库中的存放地址
		String filepath="upload"+File.separator+"storeicon"+File.separator+store.getStore_id()+".png";
		//获取项目的根目录
		String projectPath=request.getSession().getServletContext().getRealPath(File.separator);
		//如果有图片
		if(!file.isEmpty()){
			//压缩并上传图片
			CompressImageUtil.compressByWH(file,projectPath+filepath);
		}
		//将数据库地址设置到我的事业对象中
		store.setIcon(filepath);
		//System.out.println(store.toString());
		//进行修改操作
		int resultcode=storeDao.updateStoreIcon(store);
		if(resultcode>0){
			result.setMsg("更换成功");
			result.setStatus(1);
		}else{
			result.setMsg("更换失败");
			result.setStatus(0);
		}
		return result;
	}

	@Override
	public AdResult updateImageDescription(String media_id ,String description,String type) {
		AdResult result=new AdResult();
		String descriptionFinal=checkStoreImageDescLength(description);
		HashMap<String, String> map=new HashMap<>();
		int code=0;
		if(type.equals("0")){
			map.put("image_id", media_id);
			map.put("description", descriptionFinal);
			code=storeDao.updateImageDescription(map);
		} else if(type.equals("1")){
			map.put("video_id", media_id);
			map.put("description", descriptionFinal);
			code=storeDao.updateVideoDescription(map);
		}
		if(code>0){
			result.setMsg("修改成功");
			result.setStatus(1);
		}else{
			result.setMsg("修改失败");
			result.setStatus(0);
		}
		return result;
	}

	@Override
	public AdResult deleteStoreImage(String image_id,String type) {
		AdResult result=new AdResult();
		int code=0;
		if(type.equals("0")){
			code=storeDao.deleteStoreImage(image_id);
		}else if(type.equals("1")){
			code=storeDao.deleteStoreVideo(image_id);
		}
		if(code>0){
			//删除图片文件
			result.setMsg("删除成功");
			result.setStatus(1);
		}else{
			result.setMsg("删除失败");
			result.setStatus(0);
		}
		return result;
	}

	@Override
	public AdResult moveToFirst(String image_id,String type) {
		AdResult result=new AdResult();
		int code=0;
		if(type.equals("0")){
			code=storeDao.moveToFirst(image_id);
		}else if(type.equals("1")){
			code=storeDao.moveVideoToFirst(image_id);
		}
		if(code>0){
			result.setMsg("移动成功");
			result.setStatus(1);
		}else{
			result.setMsg("移动失败");
			result.setStatus(0);
		}
		return result;
	}
	
	//检查发布数据的字段长度
	public static String checkStoreImageDescLength(String description){
		String descriptionFinal=description;
		//标题处理
		if(description!=null && description.length()>20){
			descriptionFinal=description.substring(0, 50);
		}
		return descriptionFinal;
	}

	@Override
	public StoreMediaResult uploadMediaImage(HttpServletRequest request, CommonsMultipartFile[] files) {
		StoreImage storeImage=null;
		String description=null;
		String link=null;
		ArrayList<String> filePaths=new ArrayList<>();
		ArrayList<String> descs=new ArrayList<>();
		ArrayList<String> image_ids=new ArrayList<>();
		boolean isSuccess=true;
		String store_id=request.getParameter("store_id");
		//request.getParameter("store_id");
		// 定义一个结果对象一共返回
		StoreMediaResult result = new StoreMediaResult();
		// 存储当前广告多张图片的组合地址以","隔开（也是写入数据库的地址）
		//String filepath = "";
		// 获取项目的根目录
		String basePath = request.getSession().getServletContext().getRealPath(File.separator);
		if (files != null) {
			try {
				// 定义当前时间
				for(int i=0;i<files.length;i++){
					description=checkDescLength(request.getParameter("description"+i));
					link=request.getParameter("link"+i);
					descs.add(description);
					Date now = new Date();
					InputStream in = files[i].getInputStream();
					String relatedpath = "upload/storephotos/" + GenerateUniqueId.generateUniqueId()+".png";
					filePaths.add(relatedpath);
					//filepath = filepath + relatedpath;
					File file_upload = new File(basePath + relatedpath);
					FileOutputStream fos = new FileOutputStream(file_upload);
					int len = -1;
					byte[] bytes = new byte[1024];
					while ((len = in.read(bytes)) != -1) {
						fos.write(bytes, 0, len);
					}
					in.close();
					fos.close();
					storeImage=new StoreImage();
				    storeImage.setDescription(description);
					storeImage.setImage(relatedpath);
					storeImage.setStore_id(store_id);
					if(link!=null && !link.equals("")){
						storeImage.setIs_link("1");
						storeImage.setHttpaddress(link);
					}else{
						storeImage.setIs_link("0");
					}
					String image_id=GenerateUniqueId.generateUniqueId();
					image_ids.add(image_id);
					storeImage.setImage_id(image_id);
					storeImage.setAdd_time(new Date());
					int resultCode=storeDao.createStoreImage(storeImage);
					System.out.println(resultCode);
					if(resultCode<=0){
						isSuccess=false;
					}
				}
			} catch (IOException e) {
				isSuccess=false;  
				e.printStackTrace();
			}
			finally{
				//TODO
				System.out.println(isSuccess);
				if(!isSuccess){
					//删除所有文件
					for(int i=0;i<filePaths.size();i++){
						File file=new File(basePath+filePaths.get(i));
						if(file.exists()){
							file.delete();
						}
						storeDao.deleteStoreImage(image_ids.get(i));
					}
					result.setMsg("失败了");
					result.setStatus(0);
					return result;
				}
			}
		}
		//将所有关注者已读状态改成未读
		storeDao.changeReadedToZero(store_id);
		result.setMsg("上传成功");
		result.setStatus(1);
		result.setData(filePaths);
		result.setData2(descs);
		return result;
	}
	
	//检查发布数据的字段长度
	public static String checkDescLength(String desc){
		//内容处理
		if(desc!=null && desc.length()>20){
			return desc.substring(0,20);
		}
		return desc;
	}

	@Override
	public StoreMediaResult uploadMediaVideo(StoreVideo storeVideo, HttpServletRequest request,CommonsMultipartFile[] files) {
		// 定义一个结果对象一共返回
		StoreMediaResult result = new StoreMediaResult();
		//视频地址
		String videoPath = "";
		//视频缩略图地址
		String posterPath = "";
		// 获取项目的根目录
		String basePath = request.getSession().getServletContext().getRealPath(File.separator);
		// 保存相应的图片至对应的文件存储目录
		if (files != null) {
			try {
				for (int i = 0; i < files.length; i++) {
					if(i==0){
						// 定义当前时间
						Date now = new Date();
						InputStream in = files[i].getInputStream();
						String relatedpath = "upload/storevideos/" + now.getTime()+ files[i].getOriginalFilename();
						videoPath = videoPath + relatedpath;
						File file = new File(basePath + relatedpath);
						FileOutputStream fos = new FileOutputStream(file);
						int len = -1;
						byte[] bytes = new byte[1024];
						while ((len = in.read(bytes)) != -1) {
							fos.write(bytes, 0, len);
						}
						in.close();
						fos.close();
					}
					if(i==1){
						// 定义当前时间
						Date now = new Date();
						InputStream in = files[i].getInputStream();
						String relatedpath = "upload/poster/" + now.getTime()+ files[i].getOriginalFilename();
						posterPath = posterPath + relatedpath;
						File file = new File(basePath + relatedpath);
						FileOutputStream fos = new FileOutputStream(file);
						int len = -1;
						byte[] bytes = new byte[1024];
						while ((len = in.read(bytes)) != -1) {
							fos.write(bytes, 0, len);
						}
						in.close();
						fos.close();
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
				result.setMsg("失败了");
				result.setStatus(0);
				return result;
			}
			storeVideo.setAdd_time(new Date());
			storeVideo.setPoster(posterPath);
			storeVideo.setVideo(videoPath);
			String video_id=GenerateUniqueId.generateUniqueId();
			storeVideo.setVideo_id(video_id);
			int resultCode=storeDao.createStoreVideo(storeVideo);
			if(resultCode>0){
				result.setMsg("上传成功");
				result.setStatus(1);
			}
		}
		return result;
	}

}
 